CLI Options
typer.Option()
works very similarly to typer.Argument()
, but has some extra features that we'll see next.
help 说明
lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",
formal: Annotated[bool, typer.Option(help="Say hi formally.")] = False,

show_default 的用法也和 CLI Arguments 一样
必选的 CLI Options
要使 CLI Options 变为必选,只需要去掉默认值即可
lastname: Annotated[str, typer.Option()]
输入提示 prompt
当必填的 Option 缺失时,除了直接抛出错误之外,还可以使用 prompt=True
来提示用户输入
lastname: Annotated[str, typer.Option(prompt=True)]

在 prompt 中传入提示字符串,对用户更友好
lastname: Annotated[str, typer.Option(prompt="Please tell me your last name")]

二次确认提示
有时候,你想让用户再次确认输入,可以使用 confirmation_prompt=True
project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]
import typer
from typing_extensions import Annotated
def main(
project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],
):
print(f"Deleting project {project_name}")
if __name__ == "__main__":
typer.run(main)

密码 prompt
使用 hide_input=True
来开启密码模式
password: Annotated[
str, typer.Option(prompt=True, confirmation_prompt=True, hide_input=True)
],
自定义 Option 名
默认的取名方式:user_name
-> --user-name
当然可以自定义:
user_name: Annotated[str, typer.Option("--name")]